package com.dtz.rabbitmq.simple;

import java.io.IOException;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

public class Consumer {
	
	public static void main(String[] args) {
		// 1、创建连接工厂
		ConnectionFactory factory = new ConnectionFactory();
		// 2、设置连接属性
		factory.setHost("1.15.137.13");
		factory.setPort(5672);
		factory.setVirtualHost("/");
		factory.setUsername("admin");
		factory.setPassword("admin");
		
		Connection connection = null;
		Channel channel = null;
		
		try {
			// 3、获取连接
			connection = factory.newConnection("消费者");
			
			// 4、获取通道
			channel = connection.createChannel();
			
			// 5、接收消息
			channel.basicConsume("quenen1", new DeliverCallback() {
				
				@Override
				public void handle(String consumerTag, Delivery message) throws IOException {
					System.out.println("收到的消息是：" + new String(message.getBody(), "utf-8"));
				}
			}, new CancelCallback() {
				
				@Override
				public void handle(String consumerTag) throws IOException {
					System.out.println("接收消息失败");
				}
			});
			
			System.out.println("开始接收消息");
			System.in.read();
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("消息发送失败！");
		} finally {
			
			// 6: 释放连接关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
		}
	}

}
